"""
Case Type   : datakit安装
Case Name   : 【实例管理】创建openGauss实例
Create At   : 2025/5/20
Owner       : @lonely-dance
Description :
    1.输入openGauss信息，点击测试联通性
    2.添加openGauss实例
    3.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
History     :
"""

import os
import re
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.datakit_api.CommonApi import CommonApi
from testcase.utils.CommonDatakit import CommonDatakit


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.com_sh = CommonSH()
        self.pri_node = Node('PrimaryDbUser')
        self.datakit_node = Node('Datakit_Root')
        self.token = self.com_sh.get_token_value(macro.DATAKIT_PASSWD)
        self.log.info(self.token)
        self.assertNotEqual("error", self.token)
        self.com_api = CommonApi(self.token)
        self.com_datakit = CommonDatakit(self.token)
        self.user_name = re.search(r'Case\d+', os.path.basename(__file__)).group()
        self.data = {"clusterName": f"{self.pri_node.ssh_host}({self.pri_node.db_port})-1",
                     "dbType": "OPENGAUSS",
                     "deployType": "SINGLE_NODE",
                     "nodes": [{"id": "", "tabName": 1,
                                "url": f"jdbc:opengauss://{self.pri_node.ssh_host}:{self.pri_node.db_port}/postgres",
                                "urlSuffix": "", "ip": f"{self.pri_node.ssh_host}",
                                "port": self.pri_node.db_port,
                                "username": f"{self.pri_node.db_user}",
                                "password": f"{self.pri_node.db_password}",
                                "props": [{"name": "", "value": ""}], "status": 1,
                                "extendProps": "[{\"name\":\"\",\"value\":\"\"}]"}]}

    def test_base_ops(self):
        text = '----step1:输入openGauss信息，点击测试联通性 expect:成功----'
        self.log.info(text)
        response = self.com_api.post_jdbcDbClusterNode_ping(self.data)
        self.log.info(response.json())
        self.assertEqual(200, response.json()['code'], '执行失败:' + text)

        text = '----step2:添加openGauss实例， expect: 成功----'
        self.log.info(text)
        response = self.com_api.post_jdbcDbCluster_add(self.data)
        self.log.info(response.json())
        self.assertEqual(200, response.json()['code'], '执行失败:' + text)

        response = self.com_api.get_jdbcDbCluster_page(ip=self.pri_node.ssh_host)
        self.log.info(response.json())
        self.assertEqual(1, len(response.json()['rows']), '执行失败:' + text)

    def tearDown(self):
        self.log.info('----step3:清理环境----')
        self.com_datakit.delete_db()
        self.log.info(f"-----{os.path.basename(__file__)} finsh-----")
